package cn.lingyangwl.framework.core.model;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.lingyangwl.framework.tool.core.StringUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Optional;

/**
 * 分页参数, 需要分页查询的继承该类
 * @author shenguangyang
 */
@ApiModel(value = "分页参数")
public class PageParam implements Serializable {
    private static final Integer PAGE_NUM = 1;
    private static final Integer PAGE_SIZE = 20;

    @Getter
    @Setter
    @ApiModelProperty(value = "页码，从 1 开始", example = "1")
    @NotNull(message = "页码不能为空")
    @Min(value = 1, message = "页码最小值为 1")
    private Integer pageNum = PAGE_NUM;

    @Getter
    @Setter
    @ApiModelProperty(value = "每页条数，最大值为 100", example = "10")
    @NotNull(message = "每页条数不能为空")
    @Min(value = 1, message = "每页条数最小值为 1")
    @Max(value = 1000, message = "每页条数最大值为 1000")
    private Integer pageSize = PAGE_SIZE;

    @Getter
    @ApiModelProperty(value = "排序的方向desc或者asc", example = "asc")
    private String order = "asc";

    @ApiModelProperty(value = "排序列", example = "asc")
    private String orderByColumn;

    @Setter
    @ApiModelProperty(value = "开始时间", example = "2023-06-08 11:00:00")
    private String beginDate;

    @Setter
    @ApiModelProperty(value = "结束时间", example = "2023-06-08 11:00:00")
    private String endDate;

    public String getOrderBy() {
        if (StringUtils.isEmpty(orderByColumn)) {
            return "";
        }
        return StringUtils.humpToUnderline(orderByColumn) + " " + order;
    }

    public LocalDateTime getBeginLocalDateTime() {
        DateTime parse = DateUtil.parse(this.beginDate);
        return  Optional.ofNullable(parse).map(DateTime::toLocalDateTime).orElse(null);
    }

    public LocalDateTime getEndLocalDateTime() {
        DateTime parse = DateUtil.parse(this.endDate);
        return  Optional.ofNullable(parse).map(DateTime::toLocalDateTime).orElse(null);
    }

    public Date getBeginJdkDate() {
        DateTime parse = DateUtil.parse(this.beginDate);
        return  Optional.ofNullable(parse).map(DateTime::toJdkDate).orElse(null);
    }

    public Date getEndJdkDate() {
        DateTime parse = DateUtil.parse(this.endDate);
        return Optional.ofNullable(parse).map(DateTime::toJdkDate).orElse(null);
    }

    public void setOrder(String order) {
        // 兼容前端排序类型
        if ("ascending".equals(order)) {
            order = "asc";
        } else if ("descending".equals(order)) {
            order = "desc";
        }
        this.order = order;
    }
}
